<!--
 * @Author: chen qi
 * @Date: 2022-07-12 00:29:37
 * @LastEditors: chen qi
 * @LastEditTime: 2022-07-14 10:06:16
 * @Description:
-->
<template>
  <div
    :ref="`map2dChart${id}`"
    class="map2d-chart"
  ></div>
</template>

<script>
import commonMixin from '@/utils/mixin'
export default {
  name: 'mapChart2',
  mixins: [commonMixin],
  props: {
    id: {
      type: [Number, String],
      default: 1
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      // 北京,天津,上海,重庆,澳门,香港
      crowns: [110000, 120000, 310000, 500000, 820000, 810000],
      timeFn: null,
      resDebounce: null, // 防抖
      chart: null, // chart实例,
      // 各省份的数据
      allData: []
    }
  },
  mounted() {
    this.init()
    setTimeout(() => {
      this.setEffectScatterColor()
    }, 2000)
  },
  methods: {
    setEffectScatterColor() {
      // 设置颜色
      this.chart.setOption({
        series: [
          {
            name: 'effectScatter',
            itemStyle: {
              color: 'red'
            },
            animation: true
          }
        ]
      })
    },
    /**
     * @description: 初始化
     * @return {*}
     * @author: chen qi
     */
    init() {
      this.chart = this.$echarts.init(this.$refs[`map2dChart${this.id}`])
      this.resDebounce = this.debounce(this.chart.resize, 300)
      window.addEventListener('resize', this.resDebounce)
      this.chart.on('click', (params) => {
        // 清除画布
        // this.chart.clear()
        // 点击title
        if (params.componentType === 'title') {
          alert(11)
        } else if (params.componentType === 'series') {
          clearTimeout(this.timeFn)
          this.timeFn = setTimeout(() => {
            const { data } = params
            console.log(params)
            this.loadMap(data.adcode, data.name, data.level)
          }, 250)
        }
      })
      this.chart.on('dblclick', (params) => {
        console.log(params)
        const { data } = params
        clearTimeout(this.timeFn)
        let prelevel
        let adcode
        console.log(data.adcode, 'data')
        if (data.level === 'province' && data.adcode !== 710000) return
        if (data.level === 'city' || data.adcode === 710000) {
          prelevel = ''
          adcode = data.acroutes[0]
        } else if (data.level === 'district') {
        // 是否在直辖市
          if (this.isInCrowns(data.acroutes, this.crowns)) {
            if (this.allData.length === 1) {
              prelevel = 'city'
              adcode = data.acroutes[1]
            } else {
              prelevel = ''
              adcode = data.acroutes[0]
            }
          } else {
            prelevel = 'province'
            if (this.allData.length === 1) {
              adcode = data.acroutes[2]
            } else {
              adcode = data.acroutes[1]
            }
          }
        }
        this.loadMap(adcode, '', prelevel)
      })
      this.loadMap('100000', 'china')
    },

    /**
     * @description: 判断是否在直辖市内
     * @param {*} acroutes
     * @param {*} crowns
     * @return {*}
     * @author: chen qi
     */
    isInCrowns(acroutes, crowns) {
      for (let index = 0; index < acroutes.length; index++) {
        const element = acroutes[index]
        if (crowns.includes(element)) return true
      }
      return false
    },
    /**
     * @description:获取option对象
     * @param {*} options
     * @return {*}
     * @author: chen qi
     */
    getOption(options = {}) {
      const name = options.name || ''
      const effectScatters = this.allData.map(item => { return { name: item.name, value: item.center, num: item.value } }).sort((a, b) => b.num - a.num).slice(0, 4) // 地理位置数据,
      const option = {
        geo: {
          show: true,
          map: name,
          roam: false, // 鼠标滚动
          zoom: 1, // 缩放
          // 以某个地理坐标为中心
          // center: [112.982279, 28.19409],
          label: {
            show: false,
            color: '#FFFFFF'
          },
          emphasis: {
            label: {
              show: true,
              color: '#ffffff' // 选中文字颜色
            },
            itemStyle: {
              areaColor: '#2B91B7' // 高亮区域颜色
              // opacity:'0.5'
            }
          },
          /** 隐藏南海诸岛右下角小地图 */
          regions: [
            {
              name: '南海诸岛',
              /** 隐藏地图，透明度为 0 时不绘制该图形 */
              itemStyle: { opacity: 0 },
              // 隐藏文字
              label: { show: false }
            }
          ],
          itemStyle: {
            borderColor: 'rgba(17, 235, 248, 1)',
            borderWidth: 1,
            areaColor: {
              type: 'radial',
              x: 0.5,
              y: 0.5,
              r: 0.8,
              colorStops: [{
                offset: 0,
                color: 'rgba(147, 25, 28, 0)' // 0% 处的颜色
              }, {
                offset: 1,
                color: 'rgba(147, 235, 248, .2)' // 100% 处的颜色
              }],
              globalCoord: false // 缺省为 false
            },
            shadowColor: 'rgba(18, 27, 28, 1)',
            shadowOffsetX: -2,
            shadowOffsetY: 2,
            shadowBlur: 10
          }
        },
        // 当前视角的中心点。
        // center: [80, 30],
        series: [
          // 地图
          {
            name: 'map',
            type: 'map',
            map: name,
            geoIndex: 0,
            // 地面可以让整个组件有个“摆放”的地方，从而使整个场景看起来更真实，更有模型感。
            groundPlane: {
              // 是否显示地面。[ default: false ]
              show: false,
              // 地面颜色。[ default: '#aaa' ]
              color: '#aaa'
            },
            scaleLimit: {
              // 滚轮缩放的极限控制
              min: 1,
              max: 2
            },
            selectedMode: false, // 是否允许选中多个区域
            roam: false, // 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移，可以设置成 'scale' 或者 'move'。设置成 true 为都开启
            // 地区地名显示
            label: {
              show: false,
              color: '#000'
            },
            // 地区样式 鼠标滑过
            itemStyle: {
              label: {
                show: true,
                color: '#fff'
              },
              color: '#fff',
              borderColor: '#32CBE0',
              borderWidth: 1.5,
              areaColor: {
                type: 'linear-gradient',
                x: 0,
                y: 1000,
                x2: 0,
                y2: 0,
                colorStops: [
                  {
                    offset: 0.5,
                    color: '#0D59C1' // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: '#53C9C7' // 100% 处的颜色
                  }
                ],
                global: true // 缺省为 false
              },
              emphasis: {
                label: {
                  show: true,
                  color: '#fff'
                },
                borderWidth: 3,
                borderColor: 'rgba(255, 230, 175,0.8)',
                shadowColor: 'rgba(255, 230, 175,0.5)',
                shadowBlur: 30,
                textStyle: {
                  color: 'red',
                  fontSize: 12,
                  backgroundColor: 'transparent'
                },
                areaColor: new this.$echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: '#1cfbfe'
                    },
                    {
                      offset: 1,
                      color: '#3348e7'
                    }
                  ],
                  false
                )
              }
            },
            // 选中的状态
            select: {
              label: {
                show: true
              },
              itemStyle: {
                areaColor: '#0b59a3'
              }
            },
            // 地理数据
            data: this.allData
          },
          // 地图中闪烁的点
          {
            name: 'effectScatter',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            data: effectScatters,
            // symbolSize: [10, 5],
            showEffectOn: 'render',
            rippleEffect: {
              scale: 5,
              brushType: 'stroke'
            },
            hoverAnimation: true,
            label: {
              formatter: () => {
                return 1
              },
              position: 'right',
              show: false
            },
            itemStyle: {
              color: '#F46E36',
              shadowBlur: 10,
              shadowColor: '#F46E36'
            },
            zlevel: 1
          }

        ],
        animation: true
      }
      return option
    },

    /**
     * @description: 请求路径
     * @param {*} mapCode 区域代码
     * @param {*} level 行政级别
     * @return {*}
     * @author: chen qi
     */
    getMapUrl(mapCode, level) {
      let url
      // 省,市 (除台湾)
      if ((level === 'province' || level === 'city' || level === '') && mapCode !== 710000) {
        url = `https://geo.datav.aliyun.com/areas_v3/bound/${mapCode}_full.json`
      } else {
        url = `https://geo.datav.aliyun.com/areas_v3/bound/${mapCode}.json`
      }
      return url
    },

    /**
     * @description://获取数据绘制图表
     * @param {*} mapCode 区域代码
     * @param {*} name  地区名字
     * @param {*} level 行政级别
     * @return {*}
     * @author: chen qi
     */
    loadMap(mapCode, name = '', level = '') {
      const url = this.getMapUrl(mapCode, level)
      this.$axios.get(url).then(res => {
        const { data } = res
        this.allData = data.features.map(item => {
          return {
            ...item.properties,
            value: Math.round(Math.random() * 100)
          }
        }).filter(item => item.name !== '')
        this.$echarts.registerMap(name, data)
        const option = this.getOption({ name })
        this.chart.setOption(option, true, true)
      }).catch(err => {
        console.log(err)
      })
    }
  },
  destroyed() {
    window.addEventListener('resize', this.resDebounce)
  }
}
</script>

<style lang="less" scoped>
.map2d-chart {
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
